// components/shopfilter/shopfilter.ts
Component({

  /**
   * 组件的属性列表
   */
  properties: {
    showFilter: {
      type: Boolean
    },
    animation: Object,
    categoryList: Array,
    categoryIds: Array
  },
  /**
   * 组件的初始数据
   */
  data: {
    show: true as boolean,
    selectedIndex: 0, // 初始化选中的分类索引
    selectedDetailIndices: [] as Array<number>,
  },

  /**
   * 组件的方法列表
   */
  methods: {
    // 选择分类
    selectCategory(e: any): void {
      const index = e.currentTarget.dataset.index;
      this.setData({
        selectedIndex: index,
      });
    },
    // 关闭弹窗
    closeFilter(): void {
      this.triggerEvent("getCId", { ids: this.data.selectedDetailIndices, list: this.data.categoryList })
    },
    // 选择分类项
    chooseItem(e: any): void {
      // 判断数组中是否存在该元素ID,如果存在,就去除,不存在就添加
      const { categoryList, selectedIndex, selectedDetailIndices } = this.data
      const id = e.currentTarget.dataset.id
      const index = selectedDetailIndices.indexOf(id);
      if (index !== -1) {
        selectedDetailIndices.splice(index, 1)
      } else {
        selectedDetailIndices.push(id)
      }
      categoryList[selectedIndex].children!.forEach((item: CategoryModel) => {
        console.log(item)
        if (item.id == id) {
          item.choose = !item.choose
        }
      })
      this.setData({
        categoryList,
        selectedDetailIndices
      })
    },
    // 重置
    reset(): void {
      if(!this.data.categoryList.length) {
        return
      }
      this.data.categoryList.forEach((item:CategoryModel) => {
        item.children!.forEach(i => {
          i.choose = false
        })
      })
      this.setData({
        selectedDetailIndices: [],
        categoryList: this.data.categoryList,
      })
    },
  },
  lifetimes: {
    attached() {
      this.setData({
        selectedDetailIndices: this.data.categoryIds
      })
    },
  }
})